package com.zdya.combatdocuments.util;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;
import java.text.*;


@Slf4j
public class SynSystemDateUtils {
 
    public static void main(String[] args) throws Exception {
//        bw.write("time 21:35:00");
//        bw.newLine();
//        bw.write("date 2022/04/28");
        //String date = "2022/04/28";
        String time = "10:47:00"  ;
//        updateSysDateTime(date,time);
        setDateTimeBat(null,time);
    }
 
    /**
     * 修改系统时间
     * yyyy-MM-dd HH:mm:ss
     */
    public static void updateSysDateTime(String dataStr_,String timeStr_) throws Exception {
        try {
            String osName = System.getProperty("os.name");
            // Window 系统
            if (osName.matches("^(?i)Windows.*$")) {
                String cmd;
                // 格式：yyyy-MM-dd
                cmd = " cmd /c date " + dataStr_;
                Runtime.getRuntime().exec(cmd);
                // 格式 HH:mm:ss
                cmd = " cmd /c time " + timeStr_;
                String res = runAndResult(cmd);
                System.out.println("windows 时间修改" + res);
            } else if (osName.matches("^(?i)Linux.*$")) {
                // Linux 系统 格式：yyyy-MM-dd HH:mm:ss   date -s "2017-11-11 11:11:11"
                FileWriter excutefw = new FileWriter("/usr/updateSysTime.sh");
                BufferedWriter excutebw=new BufferedWriter(excutefw);
                excutebw.write("date -s \"" + dataStr_ +" "+ timeStr_ +"\"\r\n");
                excutebw.close();
                excutefw.close();
                String cmd_date ="sh /usr/updateSysTime.sh";
                String res = runAndResult(cmd_date);
                System.out.println("cmd :" + cmd_date + " date :" + dataStr_ +" time :" + timeStr_);
                System.out.println("linux 时间修改" + res);
            } else {
                System.out.println("操作系统无法识别");
            }
        } catch (IOException e) {
            e.getMessage();
        }
    }



     /**
     * 执行 脚本命令  关心结果
     * @param cmd
     * @return
     */
    public static String runAndResult(String cmd) throws Exception{
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        boolean execFlag = true;

        String uuid = UUID.randomUUID().toString().replace("-","");
        String tempFileName = "./temp" + uuid +".sh";
        try {
            String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);

            if (osName.matches("^(?i)LINUX.*$") || osName.contains("MAC")) {
                FileWriter excutefw = new FileWriter(tempFileName);
                BufferedWriter excutebw=new BufferedWriter(excutefw);
                excutebw.write(cmd + "\n");
                excutebw.close();
                excutefw.close();
                String command ="bash " + tempFileName;

                Process p = Runtime.getRuntime().exec(command);
                p.waitFor();

                br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    //sb.append("<br/>");
                    sb.append(System.lineSeparator());
                    sb.append(line);
                }
                br.close();

                br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                while ((line = br.readLine()) != null) {
                    //sb.append("<br/>");
                    sb.append(System.lineSeparator());
                    sb.append(line);
                    if (line.length() > 0){
                        execFlag = false;
                    }
                }
                br.close();

                if (execFlag){
                    log.info("exec [ {} ]  OK , result : [ {} ]",cmd ,sb.toString());
                }else {
                    throw new RuntimeException(sb.toString());
                }
            }else {
                throw new RuntimeException("不支持的操作系统类型");
            }
        } catch (Exception e) {
            log.error("exec [ {} ]  fail : {}",cmd ,e.getMessage());
            throw e;
        }finally {
            if (br != null){
                br.close();
            }
            FileUtil.del(new File(tempFileName));
            //FileUtils.deleteQuietly(new File(tempFileName));
        }
        return sb.toString();
    }


    public static void setDateTimeBat(String date,String time) {
        try {
            File temDir = new File("C:\\timeTemp");
            String filePath = "setDateTime.bat";
            File batFile = new File(temDir.getPath() + "/" + filePath);

            if (!temDir.exists()) {
                temDir.mkdir();
                batFile.createNewFile();
            }

            FileWriter fw = new FileWriter(filePath);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("@echo off\n");
            bw.write("%1 mshta vbscript:CreateObject(\"Shell.Application\").ShellExecute(\"cmd.exe\",\"/c %~s0 ::\",\"\",\"runas\",1)(window.close)&&exit\n");
            if (time != null && !"".equals(time)){
                bw.write("time "+time);
            }
            bw.newLine();
            if (date != null && !"".equals(date)){
                bw.write("date "+date);
            }
            bw.close();
            fw.close();
            Process process = Runtime.getRuntime().exec(filePath);
            process.waitFor();
            //等上面的执行完毕后再删除文件
            batFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
}